/*
 ============================================================================
 Name		: SAAppUi.cpp
 Author	  : 
 Copyright   : Copyright (c)
 All rights reserved.
 Description : CSAAppUi implementation
 ============================================================================
 */

// INCLUDE FILES
#include <avkon.hrh>
#include <aknnotewrappers.h>
#include <stringloader.h>
#include <f32file.h>
#include <s32file.h>
#include <hlplch.h>
#include <APGWGNAM.H>
#include <SMSAssist_0xEB692DC8.rsg>
#include <BAUTILS.h>                    //BaflUtils
#include <eikenv.h>                     //CEikonEnv
#include <aknmessagequerydialog.h>      //CAknMessageQueryDialog
#include <akncolourselectiongrid.h>     //CAknColourSelectionGrid

// USER INCLUDE
//#include "SA_0xEB692DC8.hlp.hrh"
#include "SA.hrh"
#include "SA.pan"
#include "SAApplication.h"
#include "SAAppView.h"
#include "SAMainView.h"
#include "SASettingslistView.h"
#include "SACommonDef.h"

// CLASS INCLUDE
#include "SAAppUi.h"

// constant


// ============================ MEMBER FUNCTIONS ===============================


// -----------------------------------------------------------------------------
// CSAAppUi::ConstructL()
// Symbian 2nd phase constructor can leave.
// -----------------------------------------------------------------------------
//
void CSAAppUi::ConstructL()
{
    // Initialise app UI with standard value.
    BaseConstructL(CAknAppUi::EAknEnableSkin);
    //BaseConstructL(CAknAppUi::EAknEnableSkin | CAknAppUi::EAknEnableMSK); 
//    HandleDisclaimerL();
    LoadSettingsL();
    CompleteConstructL();
}

void CSAAppUi::LoadSettingsL()
{
    // Read settings
    CDictionaryStore* iniFile = GetIniFileL();
    if (iniFile)
    {
        CleanupStack::PushL(iniFile);
        if (iniFile->IsPresentL(KGeneralSettingsId))
        {
            RDictionaryReadStream readStream;
            readStream.OpenLC(*iniFile, KGeneralSettingsId);
            iSettings.InternalizeL(readStream);
            CleanupStack::PopAndDestroy(&readStream);
        }
        else
        {
            iSettings.Initial();
        }
        CleanupStack::PopAndDestroy(iniFile);
    }
}

void CSAAppUi::SaveSettingsL()
{
    CSASettings* settingsPreEdit = new (ELeave) CSASettings();
    CleanupStack::PushL(settingsPreEdit);
    CDictionaryStore* iniFile = GetIniFileL();
    if (iniFile)
    {
        CleanupStack::PushL(iniFile);
        if (iniFile->IsPresentL(KGeneralSettingsId))
        {
            RDictionaryReadStream readStream;
            readStream.OpenLC(*iniFile, KGeneralSettingsId);
            settingsPreEdit->InternalizeL(readStream);
            CleanupStack::PopAndDestroy(&readStream);
        }
        // Re-externalize iSettings if changed
        if (iSettings != *settingsPreEdit)
        {
            RDictionaryWriteStream writeStream;
            writeStream.AssignLC(*iniFile, KGeneralSettingsId);
            iSettings.ExternalizeL(writeStream);
            writeStream.CommitL();
            iniFile->CommitL();
            CleanupStack::PopAndDestroy(&writeStream);
        }
        CleanupStack::PopAndDestroy(iniFile);
    }
    CleanupStack::PopAndDestroy(settingsPreEdit);
}

void CSAAppUi::CompleteConstructL()
{
    //setup views
    
    // main view
    iMainview = new (ELeave) CSAMainView;
    iMainview->ConstructL();
    AddViewL( iMainview );      // transfer ownership to CAknViewAppUi

    // settings list view
    iSettingslistView = new (ELeave) CSASettingslistView;
    iSettingslistView->ConstructL();
    AddViewL( iSettingslistView );      // transfer ownership to CAknViewAppUi
    
    SetDefaultViewL(*iMainview);
    
}
// -----------------------------------------------------------------------------
// CSAAppUi::CSAAppUi()
// C++ default constructor can NOT contain any code, that might leave.
// -----------------------------------------------------------------------------
//
CSAAppUi::CSAAppUi():iColor(KRgbMagenta), iFs(CEikonEnv::Static()->FsSession())
{
    // No implementation required
}

// -----------------------------------------------------------------------------
// CSAAppUi::~CSAAppUi()
// Destructor.
// -----------------------------------------------------------------------------
//
CSAAppUi::~CSAAppUi()
{

}

// -----------------------------------------------------------------------------
// CSAAppUi::HandleCommandL()
// Takes care of command handling.
// -----------------------------------------------------------------------------
//
void CSAAppUi::HandleCommandL(TInt aCommand)
{
    switch (aCommand)
    {
        case EEikCmdExit:
        case EAknSoftkeyExit:
        {
            Exit();
            break;
        }
        case ECommand1:     // FOR THE FUTURE
        {
            /*
            aColours
            must contains at least one element(or you'll get a panic), show at most sixteen elements.
            aNoneExist
            ETrue, show the "none" grid.
            EFalse, don't show the "none" grid.
            aNoneChosen
            As "IN" parameter, ETrue to select the first grid, EFalse to select first grid with color aColourChosen.
            As "OUT" parameter, returns whether user selected a color.
            aColourChosen
            As "IN" parameter, the initially selected color, would be ignored if it is not listed in aColours.
            As "OUT" parameter, returns whether user selected a color.
            */
            TBool noneExist = ETrue;
            TBool noneChosen = EFalse;
            TRgb  colour = KRgbMagenta;
            CArrayFixFlat<TRgb>* colours = new(ELeave) CArrayFixFlat<TRgb>(4);
            CleanupStack::PushL(colours);
            colours->AppendL(KRgbBlack);
            colours->AppendL(KRgbDarkRed);
            colours->AppendL(KRgbRed);
            colours->AppendL(KRgbGreen);
            colours->AppendL(KRgbYellow);
            colours->AppendL(KRgbDarkGreen);
            colours->AppendL(KRgbDarkYellow);
            colours->AppendL(KRgbDarkGray);
            colours->AppendL(KRgbDarkBlue);
            colours->AppendL(KRgbDarkMagenta);
            colours->AppendL(KRgbDarkCyan);
            colours->AppendL(KRgbGray);
            colours->AppendL(KRgbBlue);
            colours->AppendL(KRgbMagenta);
            colours->AppendL(KRgbCyan);
            colours->AppendL(KRgbWhite);
            CAknColourSelectionGrid *d = CAknColourSelectionGrid::NewL(colours, noneExist, noneChosen, colour);
            TBool ret = d->ExecuteLD();
            if(ret) // user selects something
            {
                iColor = colour;
            }
            CleanupStack::PopAndDestroy();
            break;           
        }
        case EHelp:
        {
            CArrayFix<TCoeHelpContext>* buf = CCoeAppUi::AppHelpContextL();
            HlpLauncher::LaunchHelpApplicationL(iEikonEnv->WsSession(), buf);
            break;
        }
        case EAbout:
        {
            CAknMessageQueryDialog* dlg = new (ELeave) CAknMessageQueryDialog();
            dlg->PrepareLC(R_ABOUT_QUERY_DIALOG);
            HBufC* title = iEikonEnv->AllocReadResourceLC(R_ABOUT_DIALOG_TITLE);
            dlg->QueryHeading()->SetTextL(*title);
            CleanupStack::PopAndDestroy(); //title
            HBufC* msg = iEikonEnv->AllocReadResourceLC(R_ABOUT_DIALOG_TEXT);
            dlg->SetMessageTextL(*msg);
            CleanupStack::PopAndDestroy(); //msg
            dlg->RunLD();
            break;
        }
        case ESettings:
        {
            ChangeToViewL(iSettingslistView->Id());
            break;
        }
        case EHide:
        {
            ShowOrHideApp();
            break;
        }
        case EAknSoftkeyBack:
        {
            ChangeToViewL(TUid::Uid(ESAMainViewId));
            break;
        }
        default:
        {
            Panic( ESAUi);
            break;
        }
    }
}

TKeyResponse CSAAppUi::HandleKeyEventL(const TKeyEvent& aKeyEvent,TEventCode aType)
{
    
}

// -----------------------------------------------------------------------------
//  Called by the framework when the application status pane
//  size is changed.  Passes the new client rectangle to the
//  AppView
// -----------------------------------------------------------------------------
//
void CSAAppUi::HandleStatusPaneSizeChange()
{
}

// -----------------------------------------------------------------------------
//  Called by the framework when the application switches to or from the foreground
//  
// -----------------------------------------------------------------------------
//
void CSAAppUi::HandleForegroundEventL(TBool aForeground)
{
    CAknAppUi::HandleForegroundEventL(aForeground);
    
    if (aForeground)
    {
        // gotcha the focus
        FadeAppInTaskListL();
    }
    else
    {
        // lose the focus
    }
}

TBool CSAAppUi::ProcessCommandParametersL( CApaCommandLine &aCommandLine )
{
    if( aCommandLine.OpaqueData().Length() == 0)
    {
        // autostart = EFalse;
        if (!iSettings.AutoRun())
        {
            Exit();
        }
    }
    return CEikAppUi::ProcessCommandParametersL(aCommandLine);
}

CArrayFix<TCoeHelpContext>* CSAAppUi::HelpContextL() const
{
//#warning "Please see comment about help and UID3..."
    // Note: Help will not work if the application uid3 is not in the
    // protected range.  The default uid3 range for projects created
    // from this template (0xE0000000 - 0xEFFFFFFF) are not in the protected range so that they
    // can be self signed and installed on the device during testing.
    // Once you get your official uid3 from Symbian Ltd. and find/replace
    // all occurrences of uid3 in your project, the context help will
    // work. Alternatively, a patch now exists for the versions of 
    // HTML help compiler in SDKs and can be found here along with an FAQ:
    // http://www3.symbian.com/faq.nsf/AllByDate/E9DF3257FD565A658025733900805EA2?OpenDocument
    CArrayFixFlat<TCoeHelpContext>* array = new (ELeave) CArrayFixFlat<TCoeHelpContext> (1);
//    CleanupStack::PushL(array);
//    array->AppendL(TCoeHelpContext(KUidSAApp, KGeneral_Information));
//    CleanupStack::Pop(array);
    return array;
}

void CSAAppUi::ShowOrHideApp(TBool aShow)
{
    TApaTaskList taskList(iCoeEnv->WsSession());
    TApaTask task = taskList.FindApp(KUidSAApp);
    if( aShow )
    {
        task.BringToForeground();        
    }
    else
    {
        task.SendToBackground();
    }
    
    // another way to show or hide own application
#if 0
    TApaTask task(iEikonEnv->WsSession( ));
                   
    // Initialise the object with the window group id of 
    // our application (so that it represent our app)
    task.SetWgId(CEikonEnv::Static()->RootWin().Identifier());

    // Request window server to bring our application
    // to foreground
    task.BringToForeground();

#endif
}

void CSAAppUi::FadeAppInTaskListL(TBool aFade)
{
    TInt wgId = iEikonEnv->RootWin().Identifier();
    RWsSession session = iEikonEnv->WsSession();
    CApaWindowGroupName* wgName = CApaWindowGroupName::NewLC(session, wgId);
    wgName->SetHidden(aFade);
    wgName->SetWindowGroupName(iEikonEnv->RootWin());
    CleanupStack::PopAndDestroy(); // wgName
}

CDictionaryStore* CSAAppUi::GetIniFileL()
{
    static_cast<CSAApplication*>(Application())->EnableIni(ETrue);
    CDictionaryStore* iniFile = Application()->OpenIniFileL(iFs);
    static_cast<CSAApplication*>(Application())->EnableIni(EFalse);
    return iniFile;
}

void CSAAppUi::ChangeToViewL(TUid aViewId)
{
    TInt viewUid = aViewId.iUid;
    
    iCurrentViewId = viewUid;
    
    if (viewUid != ESAMainViewId && viewUid != ESASettingslistViewId)
    {
//        if (iNaviPane )
//        {
//            iNaviPane->Pop(iNaviDecorator);
//            delete iNaviDecorator;
//            iNaviDecorator = NULL;
//            iTabGroup = NULL;
//            iNaviDecorator = iNaviPane->CreateNavigationLabelL(_L(""));         // ENaviLabel
//            iNaviPane->PushL(*iNaviDecorator);
//        }
        ActivateLocalViewL(aViewId);

    }
    else
    {
//        SetNaviPaneL();
//        
//        if (iTabGroup)
//            iTabGroup->SetActiveTabByIndex(viewUid-1);
    
        ActivateLocalViewL(aViewId);    

    }
}
void CSAAppUi::HandleDisclaimerL()
{
    // The disclaimer file
    _LIT(KFilename, "C:\\private\\EB692DC8\\disclaimer.txt");
    if(BaflUtils::FileExists(iFs,KFilename))
    {
        // Show the disclaimer dialog
        TBool selectedOption;
        TRAPD(showErr, selectedOption = ShowDisclaimerL(iFs,KFilename));
        if(KErrNone != showErr)
        {
            // TBM! Error handling
        }
        if(!selectedOption)
        {
            // The user canceled the disclaimer dialog. Exit the application.
            CleanupStack::PopAndDestroy();  // fsSession
            Exit();
        }
        else
        {
            // The user continued with the application launch.
            // Delete the disclaimer file so that it won't be around the next time the
            // application is run.    
            TRAPD(deleteErr, DeleteDisclaimerL(iFs, KFilename));
            if (deleteErr != KErrNone)
            {
                // TODO: Error handling
            }
        }
    }
}
TBool CSAAppUi::ShowDisclaimerL(RFs& aFs, const TDesC& aFileName)
{
    // Open the disclaimer text file
    RFile file;
    TInt openError = file.Open(aFs, aFileName, EFileRead);
    if (openError != KErrNone)
    {
        _LIT(KErrMsg, "Cannot open the disclaimer file for reading.");
        _LIT(KExitingApp, "Exiting app.");
        CEikonEnv::Static()->InfoWinL(KErrMsg, KExitingApp);
        User::Leave(openError);
    }
    CleanupClosePushL(file);
    
    // Read file size
    TInt fileSize = 0;
    TInt sizeError = file.Size(fileSize);
    if (sizeError != KErrNone)
    {
        CleanupStack::PopAndDestroy();  // file
        User::Leave(sizeError);
    }
     
    // Read file contents
    HBufC8* disclaimerText8 = HBufC8::NewLC(fileSize);
    TPtr8 disclaimerPtr = disclaimerText8->Des();
    TInt ioError = file.Read(disclaimerPtr, fileSize);
    if (ioError != KErrNone)
    {
        CleanupStack::PopAndDestroy(2);  // disclaimerText8, file
        User::Leave(ioError);
    }
     
    // Done with the file. Close it.
    file.Close();
     
    // Convert the 8-bit disclaimer text to 16-bit
    HBufC* disclaimerText = HBufC::NewLC(disclaimerText8->Length());
    disclaimerText->Des().Copy(*disclaimerText8);
     
    // Show the disclaimer dialog
    _LIT(KTitle, "SMS Assist");
    CAknMessageQueryDialog* dlg = CAknMessageQueryDialog::NewL(*disclaimerText);
    CleanupStack::PushL(dlg);
    dlg->PrepareLC(R_DISCLAIMER_DIALOG);
    dlg->SetHeaderTextL(KTitle);
    CleanupStack::Pop(dlg);
     
    TBool result = dlg->RunLD();
     
    CleanupStack::PopAndDestroy(3);  // disclaimerText, disclaimerText8, file
     
    return result;
}

void CSAAppUi::DeleteDisclaimerL(RFs& aFs, const TDesC& aFileName)
{
    // Delete the disclaimer file
    TInt deleteError = BaflUtils::DeleteFile(aFs, aFileName);
    if (deleteError != KErrNone)
    {
        User::Leave(deleteError);
    }
}

// End of File
